import { postInterfaceInfoInvoke } from '@/services/LarlyAPI_backend/interfaceInfoController';
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  message,
  Row,
  Select,
  Table,
  Typography,
} from 'antd';
import React, { useState } from 'react';
const { Title } = Typography;
const { Option } = Select;

// 请求参数类型定义
interface RequestParam {
  key: string;
  type: string;
  description: string;
  required: boolean;
}

// 模拟接口参数数据
const mockParams: RequestParam[] = [
  // { key: 'username', type: 'string', description: '用户名', required: true },
  // { key: 'password', type: 'string', description: '密码', required: true },
  // { key: 'age', type: 'number', description: '年龄', required: false },
];

const RequestMethodTag: React.FC<{ method: string }> = ({ method }) => {
  const getTagColor = (method: string) => {
    switch (method) {
      case 'GET':
        return '#4096ff';
      case 'POST':
        return '#ff4d4f';
      case 'PUT':
        return '#faad14';
      case 'DELETE':
        return '#73d13d';
      default:
        return '#8c8c8c';
    }
  };

  return (
    <span
      style={{
        backgroundColor: `${getTagColor(method)}66`,
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px',
        fontWeight: 'bold',
      }}
    >
      {method}
    </span>
  );
};

// 定义调试需要的类型
export type props = {
  id: string;
  method: string;
  url: string;
  // 请求头
  headers: Record<string, string>;
  // 请求体：请求参数
  bodyData?: Record<string, string>;
};

const DebugTab: React.FC<props> = (props) => {
  const [form] = Form.useForm();
  const [requestType, setRequestType] = useState('json');
  const [response, setResponse] = useState('');
  const { method, url, headers, bodyData } = props;

  const onFinish = async (values: any) => {
    // console.log('Received values:', values);
    const res = await postInterfaceInfoInvoke({
      id: Number(props.id),
      userRequestParams: JSON.stringify(values),
    });
    if (res.data) {
      setResponse(JSON.stringify(res.data));
      message.success('请求成功');
    }
  };

  const columns = [
    {
      title: '参数名',
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '必填',
      dataIndex: 'required',
      key: 'required',
      render: (required: boolean) => (required ? '是' : '否'),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      render: (_: any, record: RequestParam) => (
        <Form.Item name={record.key} rules={[{ required: record.required }]}>
          {record.type === 'number' ? <InputNumber style={{ width: '100%' }} /> : <Input />}
        </Form.Item>
      ),
    },
  ];

  return (
    <Card>
      <Title>
        <RequestMethodTag method={method}/>
        {url}
      </Title>
      <Title level={5}>请求参数</Title>
      <Divider style={{margin: '16px 0'}}/>

      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item label="请求格式">
              <Select value={requestType} onChange={setRequestType}>
                <Option value="json">JSON</Option>
                <Option value="formData">Form Data</Option>
                <Option value="x-www-form-urlencoded">x-www-form-urlencoded</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={18}>
            <div style={{display: 'flex', justifyContent: 'flex-end', marginTop: 24}}>
              <Button type="primary" htmlType={'submit'}>
                {' '}
                发送请求
              </Button>
            </div>
          </Col>
        </Row>
        {/*PUT/POST*/}
        {(method === 'POST' || method === 'PUT') && (
          <Form.Item label="请求体" name="userRequestParams">
            <Input.TextArea rows={6}/>
          </Form.Item>
        )}

        {/*GET*/}
        {method === 'GET' && (
          <Table<RequestParam>
            dataSource={mockParams}
            columns={columns}
            pagination={false}
            rowKey="key"
          />
        )}
      </Form>
      <Divider style={{margin: '16px 0'}}/>
      <Title level={5}>响应结果</Title>
      <div
        style={{
          backgroundColor: '#f5f5f5',
          padding: '16px',
          borderRadius: '8px',
          minHeight: '100px',
          whiteSpace: 'pre-wrap',
          fontFamily: 'monospace',
        }}
      >
        {response ? (
          <>
            {(() => {
              try {
                return JSON.stringify(JSON.parse(response), null, 2);
              } catch (e) {
                return response; // 原样显示非 JSON 内容
              }
            })()}
          </>
        ) : (
          '当前无结果'
        )}
      </div>
    </Card>
  );
};

export default DebugTab;
